{% extends 'base.html' %}
{% block title %}首页{% endblock %}
{% block head %}{% endblock %}

{% block body %}
    <div class="container" style="background-color: #ffffff;padding: 0;flex: 1;">
        <div class="container">
            <div class="row mt-3">
                <div class="col text-center">
                    <button id="newTaskButton" type="button" class="btn btn-primary" data-toggle="modal"
                            data-target="#createTaskModal">
                        新建监控任务
                    </button>
                </div>
            </div>
            <!-- 监控任务展示 -->
            <div class="container">
    <div class="row">
        <div class="col">
            <h4>自建话题监控任务</h4>
            <div id="topic_tasks" class="row row-cols-4"></div>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <h4>自建视频监控任务</h4>
            <div id="video_tasks" class="row row-cols-4"></div>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <h4>热搜话题监控任务</h4>
            <div id="hot_tasks" class="row row-cols-4"></div>
        </div>
    </div>
    <div class="row">
        <div class="col">
            <h4>视频类别监控任务</h4>
            <div id="zone_tasks" class="row row-cols-4"></div>
        </div>
    </div>
</div>
        </div>

        <!-- 创建任务弹窗 -->
        <div class="modal fade" id="createTaskModal" tabindex="-1" role="dialog" aria-labelledby="createTaskModalLabel"
             aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="createTaskModalLabel">选择创建任务类型</h5>
                        <button id="backIndex" type="button" class="close" data-dismiss="modal" aria-label="Close"
                                onclick="clean_caches()">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <button type="button" class="btn btn-primary" data-toggle="modal"
                                data-target="#createTopicTaskModal"
                                data-dismiss="modal" onclick="get_hot()">
                            创建监控话题任务
                        </button>
                        <button type="button" class="btn btn-primary" data-toggle="modal"
                                data-target="#createVideoTaskModal"
                                data-dismiss="modal">
                            创建监控指定视频任务
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 创建监控话题任务 -->
        <div class="modal fade" id="createTopicTaskModal" tabindex="-1" role="dialog"
             aria-labelledby="createTopicTaskModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="createTopicTaskModalLabel">输入话题并选择视频</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <!-- 话题输入字段 -->
                        <div class="form-group">
                            <div style="display: flex; justify-content: space-between;">
                                <div><label for="topicInput">输入话题</label></div>
                                <div style="align-self: flex-end;">
                                    <button id="submitBtn"
                                            style="display: none; background-color: #F15230; color: white; padding: 8px 20px; border: none; border-radius: 5px;">
                                        提交
                                    </button>
                                </div>
                            </div>
                            <div class="input-group">
                                <input type="text" class="form-control" id="topicInput">
                                <div class="input-group-append" id="searchButton">
                                    <button class="btn btn-outline-secondary" type="button"
                                            onclick="topics_search(document.getElementById('topicInput').value)">搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div id="hotTopics" class="mt-3"></div>
                        <div id="searchResults" class="mt-3"
                             style="display: grid; grid-template-columns: repeat(5, 1fr); grid-gap: 10px;"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 创建监控指定视频任务 -->
        <div class="modal fade" id="createVideoTaskModal" tabindex="-1" role="dialog"
             aria-labelledby="createVideoTaskModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="createVideoTaskModalLabel">输入视频BV号</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <!-- Input field for video BV id -->
                        <div class="form-group">
                            <label for="videoInput">输入视频BV号</label>
                            <input type="text" class="form-control" id="videoInput">
                            <div class="input-group-append" id="subButton">
                                <button class="btn btn-outline-secondary" type="button"
                                        onclick="create_video_task(document.getElementById('videoInput').value)">提交
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 创建任务成功 -->
        <div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel"
             aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalLabel">任务状态</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        创建任务成功！
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block js %}
    <script>
        $(document).ready(function () {
            function fetchAndDisplayTasks(url, containerId) {
                $.ajax({
                    url: url,
                    method: 'GET',
                }).done(function (data) {
                    data.data.task.forEach(function (task) {
                        var taskHtml = `<div class="col mb-4" onclick="task_detail(${task.id})">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">${task.task_name}</h5>
                            </div>
                        </div>
                    </div>`;
                        $(containerId).append(taskHtml);
                    });
                });
            }

            fetchAndDisplayTasks('/show_topic_tasks', '#topic_tasks');
            fetchAndDisplayTasks('/show_video_tasks', '#video_tasks');
            fetchAndDisplayTasks('/show_hot_tasks', '#hot_tasks');
            fetchAndDisplayTasks('/show_zone_tasks', '#zone_tasks');
        });


        function task_detail(task_id) {
            const task_url = '/task/detail/' + task_id;  // 构建不带查询参数的URL
            window.location.href = task_url;  // 直接跳转到新的URL
        }

        {#得到并展示十个热点话题#}

        function get_hot() {
            $.ajax({
                url: 'get_hot',
                method: 'GET',
            }).done(function (data) {
                    clean_caches();
                    data.data.trending.list.forEach(function (topic) {
                        let keyword = topic.keyword;
                        var topicHtml = '<p class="card-text" onclick="topics_search(' + "'" + keyword + "'" + ')">' + keyword + '</p>';
                        $('#hotTopics').append(topicHtml);
                    });
                },
            ).fail(function (jqXHR, textStatus, errorThrown) {
                // 请求失败的处理
                console.error("Request failed: " + textStatus + ", " + errorThrown);
                if (jqXHR.status) {
                    switch (jqXHR.status) {
                        case 404:
                            alert("未找到热门话题。");
                            break;
                        case 500:
                            alert("服务器错误，请稍后重试。");
                            break;
                        default:
                            alert("发生未知错误，请联系管理员。");
                    }
                } else {
                    alert("发生未知错误，请检查网络连接。");
                }
            });
        }


        {#搜索绑定事件#}
        document.getElementById("topicInput").addEventListener("keypress", function (event) {
            if (event.key === "Enter") {
                topics_search();
            }
        });

        {#清除上次的缓存#}

        function clean_caches() {
            $("#topicInput").val("");
            document.getElementById("submitBtn").style.display = "none";
            $("#searchResults").empty();
            $("#hotTopics").empty();
        }

        let selectedVideos = [];
        {#搜索关键字并返回20个结果#}

        function topics_search(keyword) {
            $.ajax({
                url: '{{ url_for("base.topics_search") }}?keyword=' + keyword,
                method: "GET",
                contentType: 'application/json',
                success: function (response) {
                    console.log(response);
                    $('#topicInput').val(keyword);
                    $("#searchResults").empty();
                    $("#hotTopics").empty();
                    document.getElementById("submitBtn").style.display = "block";

                    if (response[0] === 'video' && Array.isArray(response[1])) {
                        response[1].forEach(function (videoData) {
                            let imageUrl = videoData.pic;
                            // 使用后端代理请求图片
                            $.ajax({
                                url: '{{ url_for("base.proxy_image") }}',
                                method: "POST",
                                data: {imageUrl: imageUrl},
                                success: function (imageData) {
                                    let videoHTML =
                                        `<style>p {margin: 2px 0;}</style>
            <div style=" font-size: 10px; overflow: hidden;text-overflow: ellipsis; white-space: nowrap;" class="video-item" id="${videoData.bvid}">
            <input type="checkbox" style="display: none" class="video-checkbox" value="${videoData.bvid}">
            <img src="data:image/jpeg;base64,${imageData.imageData}" alt="Video Cover" width="140" height="80">
            <p>${videoData.title}</p>
            <p>${videoData.author} <span style="float: right;">${videoData.duration}</span></p>
            <p>发布时间: ${new Date(videoData.pubdate * 1000).toLocaleString()}</p>
        </div>`;
                                    $("#searchResults").append(videoHTML);
                                }
                            });
                        })

                    }
                }
            })
        }

        {#搜索结果的多选框#}
        $(document).ready(function () {
            $("#searchResults").on("click", ".video-item", function () {
                const bvid = $(this).attr("id");
                if (selectedVideos.includes(bvid)) {
                    selectedVideos = selectedVideos.filter(item => item !== bvid);
                    $(this).css('border', 'none'); // 取消选中样式
                    // 或者使用removeClass来移除选中样式类
                    // $(this).removeClass("selected-item-style");
                } else {
                    selectedVideos.push(bvid);
                    $(this).css('border', '2px solid blue'); // 应用选中样式
                    // 或者使用addClass来添加选中样式类
                    // $(this).addClass("selected-item-style");
                }

                console.log(selectedVideos);
            });
        });

        {#多选视频后的提交#}
        $("#submitBtn").click(function () {
            $.ajax({
                url: '/task/create_topic_tasks',
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({videos: selectedVideos, task_name: $('#topicInput').val()}),
            }).done(function (response) {
                    console.log(response); // 处理成功的逻辑
                    $('#successModal').modal('show'); // 显示模态框
                    setTimeout(function () {
                        $('#successModal').modal('hide'); // 一秒后隐藏模态框
                        window.location.reload(); // 刷新页面
                    }, 1000); // 1000毫秒 = 1秒
                },
            ).fail(function (jqXHR, textStatus, errorThrown) {
                // 请求失败的处理
                console.error("Request failed: " + textStatus + ", " + errorThrown);
                if (jqXHR.status) {
                    switch (jqXHR.status) {
                        case 404:
                            alert("未找到指定的监控任务。");
                            break;
                        case 500:
                            alert("服务器错误，请稍后重试。");
                            break;
                        default:
                            alert("发生未知错误，请联系管理员。");
                    }
                } else {
                    alert("发生未知错误，请检查网络连接。");
                }
            });
        });

        {#单选视频后的提交#}

        function create_video_task(video_bvid) {
            $.ajax({
                url: '/task/create_video_tasks',
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({video_bvid: video_bvid}),
            }).done(function (response) {
                    console.log(response); // 处理成功的逻辑
                    $('#successModal').modal('show'); // 显示模态框
                    setTimeout(function () {
                        $('#successModal').modal('hide'); // 一秒后隐藏模态框
                        window.location.reload(); // 刷新页面
                    }, 1000); // 1000毫秒 = 1秒
                },
            ).fail(function (jqXHR, textStatus, errorThrown) {
                // 请求失败的处理
                console.error("Request failed: " + textStatus + ", " + errorThrown);
                if (jqXHR.status) {
                    switch (jqXHR.status) {
                        case 404:
                            alert("未找到指定的监控任务。");
                            break;
                        case 500:
                            alert("任务建立出错，请检查视频bvid是否正确");
                            break;
                        default:
                            alert("发生未知错误，请联系管理员。");
                    }
                } else {
                    alert("发生未知错误，请检查网络连接。");
                }
            });
        }

    </script>

{% endblock %}

